# --*-- coding:utf8 --*--

from tools import conf
from mapping.dataNode import dataNode
from mapping.work import loadsheet, parentNode, PieData


def parseData(name):
    sheet_object = loadsheet(name)
    nrows = sheet_object.nrows
    for row in range(1, nrows):
        insertNode(name, sheet_object, row)


def insertNode(name, itera, row):
    def insert(myNode, level):
        value = itera.cell_value(row, conf.destructive_values[name]["colflag"][level])
        if myNode.version:
            return myNode.updateNode(
                [int(itera.cell_value(row, i)) for i in conf.destructive_values[name]["colflag"][4:]], 1)
        if not myNode.son.get(value):
            Node = dataNode(value, len(conf.destructive_values[name]["colflag"]) - 4,
                            start=itera.cell_value(row, conf.destructive_values[name]["colflag"][4]),
                            end=itera.cell_value(row, conf.destructive_values[name]["colflag"][5]))
            myNode.son[value] = Node
            if level == 2:
                Node.version = itera.cell_value(row, conf.destructive_values[name]["colflag"][3])
            return myNode.updateNode(list(insert(Node, level + 1)), 4)
        else:
            if level == 2:
                if myNode.son.get(value).version <= itera.cell_value(row, conf.destructive_values[name]["colflag"][3]):
                    myNode.son.get(value).version = itera.cell_value(row, conf.destructive_values[name]["colflag"][3])
                    return myNode.updateNode(list(myNode.son.get(value).updateNode(
                        [int(itera.cell_value(row, i)) for i in conf.destructive_values[name]["colflag"][4:]], 2)), 3)
            if myNode.son.get(value).changeV:
                myNode.son.get(value).changeV = False
                return myNode.updateNode(list(insert(myNode.son.get(value), level + 1)), 3)
            return myNode.updateNode(list(insert(myNode.son.get(value), level + 1)), 4)

    insert(parentNode, 0)


# if __name__ == "__main__":
#     down_merge()
#
#     for name in conf.destructive_values.keys():
#         parseData(name)
#
#         for x, y in enumerate(conf.destructive_values[name]["colname"]):
#             Pie.myPie(PieData(x), y)
